const  express= require("express");
const  app=express();

app.use(express.static("./views"));
const  bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));

const  mysql=require("mysql");
const  conn=mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"root",
    database:"node_001"
});
app.get("/",(req,res)=>{
    res.send("请求后台API接口成功！");
   
});
/* 获取所有英雄接口 */
app.get("/getallhero",(req,res)=>{
    const  sql="select  *  from  heros";
    conn.query(sql,(err,result)=>{
        if(err) return  res.send({status:500,message:"查询失败",data:null});
        res.send({status:200,message:"查询成功",data:result});
    });
});

/* 添加英雄接口 */
app.post("/addhero",(req,res)=>{
    // const  sql="select  *  from  heros";
    // conn.query(sql,(err,result)=>{
    //     if(err) return  res.send({status:500,message:"查询失败",data:null});
    //     res.send({status:200,message:"查询失败",data:result});
    // });
    const  hero=req.body;
    const  dt=new  Date();
    const  y=dt.getFullYear();
    const  m=(dt.getMonth()+1).toString().padStart(2,"0");
    const  d=dt.getDate().toString().padStart(2,"0");

    const  hh=dt.getHours().toString().padStart(2,"0");
    const  mm=dt.getMinutes().toString().padStart(2,"0");
    const  ss=dt.getSeconds().toString().padStart(2,"0");

    hero.ctime=y+"-"+m+"-"+d+" "+hh+":"+mm+":"+ss;
   console.log(hero);

   const  sql="insert  into  heros set ?"
   conn.query(sql,hero,(err,result)=>{
        if(err) return  res.send({status:500,message:err.message,data:null});
        res.send({status:200,message:"添加成功",data:null});
   }); 
});

/* 根据id获取用户信息 */
app.get("/gethero/:id",(req,res)=>{
    const sql="select  *  from  heros  where  id=?";
    const id=req.params.id;
    conn.query(sql,id,(err,result)=>{
        if(err) return  res.send({status:500,message:"查询失败",data:null});
        res.send({status:200,message:"查询成功",data:result});
    })
})

/* 根据id更新英雄信息 */
app.post("/updatehero/:id",(req,res)=>{

    const sql="update  heros set ?  where  id=?";
    const id=req.params.id;
    const newInfo=req.body;
    conn.query(sql,[newInfo,id],(err,result)=>{
        if(err) return  res.send({status:500,message:"更新失败",data:null});
        res.send({status:200,message:"更新成功",data:result});
    });
});

/* 根据id软删除英雄信息 */
app.get("/deletehero/:id",(req,res)=>{
    const sql="update heros  set isdel=0 where id=?";
    const id=req.params.id;
    conn.query(sql,id,(err,result)=>{
        if(err) return  res.send({status:500,message:"软删除失败",data:null});
        res.send({status:200,message:"软删除成功",data:result});
    })
})

app.listen(2100,()=>{
    console.log('server running at http://127.0.0.1:2100') 
});
